package com.zhengx.blelib;


import com.zhengx.blehelper.MessageDecoder;

import java.util.Arrays;

/**
 * name：LineBasedFrameDecoder
 * class: 按结束符解码
 * author: zhengx
 * create_time: 2018/10/29
 */
public class LineCustomMessageDecoder extends MessageDecoder {
    /*数据分隔符号*/
    private byte[] delim;

    public LineCustomMessageDecoder() {
        this(new byte[]{0x0d, 0x0a});
    }

    public LineCustomMessageDecoder(byte[] delim) {
        this.delim = delim;
    }

    @Override
    public boolean decode(byte[] source) {
        if (source.length >= 2 && source.length % 20 != 0 &&
                Arrays.equals(subBytes(source, source.length - 2, 2), delim)) {
            return true;
        }
        return false;
    }

    private byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i=begin;i<begin+count; i++) bs[i-begin] = src[i];
        return bs;
    }
}
